import { Component, OnInit, OnChanges,ViewChild,TemplateRef} from "@angular/core";
import { NzNotificationService, NzModalSubject, NzModalService } from "ng-zorro-antd";
import { PartyBean } from "../../../user/party/bean/party.bean";
import { HttpServcie } from "../../../../service/http.service";
import { Router, ActivatedRoute } from "@angular/router";
import { UserBean } from "../../../user/user/bean/user.bean";
import { Config } from "../../../../service/config";
import { elevatorPlaces } from "../../../../service/constant/elevatorPlaceConstant";
import {PublicRandomSelect} from "../bean/public-random.select";
import * as moment from "moment";

@Component({
    selector: "public-random-select",
    templateUrl: "public-random-select.html",
    styleUrls: ["public-random-select.scss"]
})
export class PublicRandomSelectPage implements OnInit, OnChanges {

    config: any;
    // 定义电梯类型
    public elevatorType:any=[];
    // 定义电梯类型选中数据
    public elevatorTypeParam:any;
    // 定义电梯梯龄选中数据
    public elevatorAgeParam:any;
    // 定义电梯场所
    elevatorPlaces = elevatorPlaces;
    // 定义电梯场所选中参数
    public elevatorPlaceParam:any;
    // 定义实体类参数
    randomSelect: PublicRandomSelect = new PublicRandomSelect();
    // 定义返回的数据
    public resultDate:any=[];
    // 定义返回的总条数
    public total:any=0;
    // 定义机构Id
    public partyId:any;
    //定义机构级别
    public partyLevel : any;
    // 定义单位返回数据
    public unitList:any=[];
    // 定义单位选中数据
    public unitParam:any;
    // 定义用户类型
    public userType:any;
    // 定义监察类型返回的数据
    public checkUserList:any=[];
    // 定义监察类型返回的总数据
    public checkUserListLength:any=0;
    // 定义人员比例
    public personPercent: any;
    // 定义通过人员比例计算后得到的人数
    public personselecttotal: any;
    // 定义单位过滤后的数据集合
    public filterData:any=[];
    // 定义单位过滤后的数据长度
    public filterDataLength:any;

    // 定义人员开始抽取按钮
    public pbuttonName: any = '开始抽取';
    public pstartSel: boolean = true;
    // 定义人员结束按钮
    public pendSel: boolean = false;
    public persondata = [];//人员 id ,名字， 类型
    // 定义人员编号5位显示地
    public presultbox1: any = 0;
    public presultbox2: any = 0;
    public presultbox3: any = 0;
    public presultbox4: any = 0;
    public presultbox5: any = 0;
    // 定义人员定时器
    public ptime: any = 0;
    // 定义人员数组下标
    public pkey: any = 0;
    // 定义人员 抽选中的名单
    public personSelected: any = [];
    // 定义人员编号集合
    public checkUserNoList:any=[];
    // 定义人员 抽取比例（计算好的数量）
    public personNum: any = 0;
    // 人员按钮状态未开始还是结束
    public pbtn: boolean = true;

    // 定义机构百分比
    public partyPercent: any;
    // 定义通过单位比例计算后得到的单位数
    public partyselecttotal: any;    //将要抽选出的个数
    // 定义单位 抽取比例（计算好的数量）
    public unitNum : any = 0;
    // 定义种子机构
    public data = [];
    // 定义单位 抽选中的名单
    public unitSelection = [];    //机构选中的名单
    // 定义单位按钮状态未开始还是结束
    public btn: boolean = true;
    // 定义机构数组下标
    public key: any = 0;
    // 定义机构定时器
    public time: any = 0;

    // 定义机构实体对象
    public partyBean: PartyBean = new PartyBean();
    // 定义机构编号5位显示地
    public resultbox1: any = 0;
    public resultbox2: any = 0;
    public resultbox3: any = 0;
    public resultbox4: any = 0;
    public resultbox5: any = 0;

    // 定义机构
    public buttonName: any = '开始抽取';
    public startSel: boolean = true;
    public endSel: boolean = false;
    // 定义机构
    public selectedList: any = ''; //机构
    public pselectedList: any = ''; //人员
    // 定义用来看机构详情用
    public partyData: any = {};    //
    public currentModal: NzModalSubject;

    // 定义分配后的数据列表
    public distribution:any=[];

    //人员实体对象
    userBean: UserBean = new UserBean();
    usertotal: any = 0; //列表展示用
    userPageSize = 10; //列表展示用 
    partyEnd = false;
    userEnd = false;
    partyPersonList = [];    //最终结果集
    publicRandomId: any
    partyType: any = '';


    // 定义传入后台参数
    public unitMultiple:any;
    public userTypeMultiple:any;

    // 定义查询后自动展开列表
    public flags =false;
    public userflags = false;

    // 计划名称
    public planName:any;

    // 实施时间
    public beginTime:any=null;
    public endTime:any=null;

    // 对话框的变量
    public isVisible = false;
    // 動畫效果變量
    public isShow = false;

    public clike:any=true;

    @ViewChild('showModel') showModel: TemplateRef<any>;
    constructor(
        private _notification: NzNotificationService,
        private httpServcie: HttpServcie,
        private router: Router,
        private nsub: NzModalSubject,
        private modalService: NzModalService,
        private activatedRoute: ActivatedRoute,
    ) {
        this.activatedRoute.params.subscribe(data => {
            this.publicRandomId = data.publicRandomId;
            this.planName = data.planName;
        });
        this.config = Config;
        this.partyId = JSON.parse(window.localStorage.getItem("user")).partyId;
        this.partyLevel = JSON.parse(window.localStorage.getItem("user")).partyLevel;
        this.randomSelect.pageSize = 10;
        this.randomSelect.currentPage = 1;


    }

    /**
     *获取电梯类型
     */
    elevatorPlace() {
      this.httpServcie.queryelevatorTypeList().subscribe(data => {
        if (data.status === 200) {
          this.elevatorType = data.data.list;
          this.total = data.data.total;
        } else {
          this._notification.create("error", "错误提示", data.message);
          return false;
        }
      });
    }
    ngOnInit() {

        //初始化电梯类型6种
        this.elevatorPlace();
        // 初始化监管单位
        this.findUnit();
    }
    ngOnChanges() {

    }

  /**
   * 查询种子数据
   */
  getElevatorListss(){
    this.randomSelect.partyLevel = this.partyLevel;
    this.randomSelect.parentId = this.partyId;
    let flag:boolean=false;
    if(this.elevatorTypeParam !=null && this.elevatorTypeParam !=""){
      this.randomSelect.elevatorTypeParam = this.elevatorTypeParam.join(",");
      flag = true;
    }
    if(this.elevatorAgeParam !=null && this.elevatorAgeParam !=""){
      this.randomSelect.elevatorAgeParam = this.elevatorAgeParam.join(",");
      flag = true;
    }
    if(this.elevatorPlaceParam !=null && this.elevatorPlaceParam !=""){
      this.randomSelect.elevatorPlaceParam = this.elevatorPlaceParam.join(",");
      flag = true;
    }
    if(! flag){
      this._notification.create("warning", "警告提示", "请至少选择一种查询条件");
      return false;
    }
    console.log(this.randomSelect);
    this.flags=true;
    this.httpServcie.getElevatorList(this.randomSelect).subscribe(data => {
        if (data.status === 200) {
          console.log(data);

          this.resultDate = data.data.list;
          this.total = data.data.total;
          this.filterData = data.data.unitlist;
          this.filterDataLength = data.data.unitlist.length;

          this.filterData.forEach(party => {
            if ((party.usedPartyId + '').length == 1) {
              party['unNo'] = '0000' + party.usedPartyId;
            }
            if ((party.usedPartyId + '').length == 2) {
              party['unNo'] = '000' + party.usedPartyId;
            }
            if ((party.usedPartyId + '').length == 3) {
              party['unNo'] = '00' + party.usedPartyId;
            }
            if ((party.usedPartyId + '').length == 4) {
              party['unNo'] = '0' + party.usedPartyId;
            }
            if ((party.usedPartyId + '').length == 5) {
              party['unNo'] = party.usedPartyId;
            }
            this.data.push(party);
          });

        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  /**
   * 主体单位导出
   */
  export() {
    let flag: boolean = false;

    if (this.elevatorTypeParam != null && this.elevatorTypeParam != "") {
      this.randomSelect.elevatorTypeParam = this.elevatorTypeParam.join(",");
      flag = true;
    }
    if (this.elevatorAgeParam != null && this.elevatorAgeParam != "") {
      this.randomSelect.elevatorAgeParam = this.elevatorAgeParam.join(",");
      flag = true;
    }
    if (this.elevatorPlaceParam != null && this.elevatorPlaceParam != "") {
      this.randomSelect.elevatorPlaceParam = this.elevatorPlaceParam.join(",");
      flag = true;
    }
    if (!flag) {
      this._notification.create("warning", "警告提示", "请至少选择一种查询条件");
      return false;
    }
    this.httpServcie.exportRandomPort(this.randomSelect).subscribe(data => {
      if (data.status == 200) {
        this.download(data.data.fileUrl, data.data.fileName);
        this._notification.create('success', '提示', "导出成功");
      } else {
        this._notification.create('error', '提示', "导出失败");
      }
    })
  }

  /**
   * 通过路径下载
   * @param url
   * @param name
   */
  download(url, name) {
    let link = document.createElement('a');
    let body = document.querySelector('body');

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(blob => {
      link.href = window.URL.createObjectURL(blob);
      link.download = name;
      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    });
  }
  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }

  /**
   * 获取单位
   */
  findUnit() {
    this.httpServcie.findUnit({"id":this.partyId}).subscribe(data => {
        if (data.status === 200) {
          this.unitList = data.data;
          console.log(this.unitList);
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  /**
   * 查询负责人种子数据
   */
  queryUnit() {
    if(this.unitParam !=null && this.unitParam !=""){
        this.unitMultiple = this.unitParam.join(",");
    }else{
      this._notification.create("warning", "警告提示", "请选择单位数据");
      return false;
    }
    if(this.userType != null && this.userType !=""){
      this.userTypeMultiple = this.userType.join(",");
    }else{
      this._notification.create("warning", "警告提示", "请选择用户类型");
      return false;
    }
    this.userflags = true;
    this.httpServcie.queryUnit({"unitParam":this.unitMultiple,"userType":this.userTypeMultiple}).subscribe(data => {
        if (data.status === 200) {
          console.log(data);
          this.checkUserList = data.data;

          if(this.checkUserList !=null && this.checkUserList.length>0){
            for(let i=0;i<this.checkUserList.length;i++){
              let party = this.checkUserList[i];
              if ((party.id + '').length == 1) {
                party['no'] = '0000' + party.id;
              }
              if ((party.id + '').length == 2) {
                party['no'] = '000' + party.id;
              }
              if ((party.id + '').length == 3) {
                party['no'] = '00' + party.id;
              }
              if ((party.id + '').length == 4) {
                party['no'] = '0' + party.id;
              }
              if ((party.id + '').length == 5) {
                party['no'] = party.id;
              }
              this.persondata.push(party);
            }
          }
          this.checkUserListLength = data.data.length;
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  /**
   * 人员编号百分比计算
   */
  personperChange() {
    if (this.personPercent > 100 || this.personPercent <= 0) {
      this.personPercent = 0;
      this._notification.create("error", "错误", "请输入 0-100");
      return false;
    }
    this.personselecttotal = Math.round(this.checkUserListLength * (this.personPercent) / 100);
    this.personNum = this.personselecttotal;
  }


  /**
   * 定时开始器 人员
   */
  runTimePerson() {
    clearInterval(this.ptime);
    this.ptime = setInterval(() => {
      this.pkey = Math.floor(Math.random() * (this.persondata.length - 1));
      let tel = this.persondata[this.pkey].no;
      let tela = tel.split("");
      this.presultbox1 = tela[0];
      this.presultbox2 = tela[1];
      this.presultbox3 = tela[2];
      this.presultbox4 = tela[3];
      this.presultbox5 = tela[4];
    }, 50);
  };

  /**
   *  再次开始抽取人员
   */
  startPerson() {
    if (this.clike) {
      if (this.personNum == 1) {
        this._notification.create("info", "提示", "抽取条数应大于1条");
        return false;
      }
    }
    if (this.pbtn) {
      if ((this.personNum <= 0)) {
        if (this.personSelected.length > 0) {
          this._notification.create("info", "提示", "抽取已完成");
        }
        return;
      } else {
        this.pbtn = false;
        this.pbuttonName = "结束抽取";
        this.pstartSel = false;
        this.pendSel = true;
        this.runTimePerson();
      }
    } else {
      this.pbtn = true;
      this.pbuttonName = "开始抽取";
      this.pstartSel = true;
      this.pendSel = false;
      this.endTrunPerson();
    }
  };

  /**
   * 停止转动数字 人员
   */
  endTrunPerson() {
    this.clike=false;
    clearInterval(this.ptime);
    this.personSelected.unshift(this.persondata[this.pkey]);
    this.pselectedList = "<p>第" + this.personNum + "号：" + this.persondata[this.pkey].id + '-' + this.persondata[this.pkey].userName + "</p>" + this.pselectedList;
    this.persondata.splice(this.pkey, 1);
    this.personNum--;
    if (this.personNum == 0) {
      if (this.personSelected.length > 0) {
        this.userEnd = true;
        this._notification.create("info", "提示", "抽取已完成");
      }
      this.userEnd = true;
      this.selectedList = "<p>抽取结束</p>" + this.selectedList;
    };
  };

  /**
   * 定义机构百分比
   */
  partyperChange() {
    if (this.partyPercent > 100 || this.partyPercent <= 0) {
      this.partyPercent = 0;
      this._notification.create("error", "错误", "请输入 0-100");
      return;
    }
    this.partyselecttotal = Math.round(this.filterDataLength * (this.partyPercent) / 100);
    this.unitNum = this.partyselecttotal;
  }

  /**
   *开始定时器  机构
   */
  runTime() {
    clearInterval(this.time);
    this.time = setInterval(() => {
      this.key = Math.floor(Math.random() * (this.data.length - 1));
      let tel = this.data[this.key].unNo;
      let tela = tel.split("");
      this.resultbox1 = tela[0];
      this.resultbox2 = tela[1];
      this.resultbox3 = tela[2];
      this.resultbox4 = tela[3];
      this.resultbox5 = tela[4];
    }, 50);
  };

  /**
   * 再次开始抽取  机构
   */
  start() {
    if (this.btn) {
      if ((this.unitNum <= 0)) {
        if (this.unitSelection.length > 0) {
          this._notification.create("info", "提示", "抽取已完成");
        }
        return;
      } else {
        this.btn = false;
        this.buttonName = "结束抽取";
        this.startSel = false;
        this.endSel = true;
        this.runTime();
      }
    } else {
      this.btn = true;
      this.buttonName = "开始抽取";
      this.startSel = true;
      this.endSel = false;
      this.endTrun();
    }
  };

  /**
   * 停止转动数字  机构
   */
  endTrun() {
    clearInterval(this.time);
    this.unitSelection.unshift(this.data[this.key]);
    this.selectedList = "<p>第" + this.unitNum + "家：" + this.data[this.key].seqNo + '-' + this.data[this.key].partyName + "</p>" + this.selectedList;
    this.data.splice(this.key, 1);
    this.unitNum--;
    if (this.unitNum == 0) {
      if (this.unitSelection.length > 0) {
        this.partyEnd = true;
        this._notification.create("info", "提示", "抽取已完成");
      }
      this.selectedList = "<p>抽取结束</p>" + this.selectedList;
    }
    ;
  };

  /**
   * 点击开始分配
   */
  startDistribution(){
    this.httpServcie.startDistribution({"person":this.personSelected,"unit":this.unitSelection}).subscribe(data => {
        if (data.status === 200) {
          this.isShow = true;
          setTimeout(()=>{
            this.isShow = false;
            this.distribution = data.data;
            console.log(this.unitList);
            this._notification.create("success", "成功提示", "分配成功");
          },4000);
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  /**
   * 导出分配结果
   */
  exportDistribution() {
    let partyName =  JSON.parse(window.localStorage.getItem("user")).partyName;
    this.httpServcie.exportDistribution({"resuList": this.distribution,"partyName":partyName}).subscribe(data => {
      if (data.status == 200) {
        this.download(data.data.fileUrl, data.data.fileName);
        this._notification.create('success', '提示', "导出成功");
      } else {
        this._notification.create('error', '提示', "导出失败");
      }
    })
  }

  /**
   * 将筛选的计划导入到现场监督计划中
   */

  importSupervise(titleforget, contentforget, footerforget) {
    this.currentModal = this.modalService.open({
      title: titleforget,
      content: contentforget,
      footer: footerforget,
      maskClosable: false,
      width: 600,
      style: {
        top: "20%"
      },

      onOk() {
        console.log("Click ok");
      }
    });
  }


  saveData() {

    if(this.beginTime !=null && this.beginTime !=undefined){
      this.beginTime =  moment(this.beginTime).format("YYYYMMDD");
    }else{
      this._notification.create('error', '提示', "请输入开始时间");
      return false;
    }

    if(this.endTime !=null && this.endTime !=undefined){
      this.endTime =  moment(this.endTime).format("YYYYMMDD");
    }else{
      this._notification.create('error', '提示', "请输入结束时间");
      return false;
    }

    if (this.beginTime > this.endTime) {
      this._notification.create('error', '错误', "开始时间不能大于结束时间");
      return false;
    }
    let user = JSON.parse(window.localStorage.getItem("user"));
    let param={
      "beginTime":this.beginTime,
      "endTime":this.endTime,
      "randomId":this.publicRandomId,
      "planName":this.planName,
      "userId":user.id,
      "userName":user.userName,
      "partyId":user.partyId,
      "partyName":user.partyName,
      "resuList": this.distribution
    }
    this.httpServcie.addPublicRandomResult(param).subscribe(data => {
      if (data.status == 200) {
        this.isVisible = true;
        this._notification.create("success", "成功", "保存结果成功,");
        this.currentModal.destroy();
      }else {
        this._notification.create("error", "失败提示", data.message);
        return;
      }
    })
  }

  toBack() {
    window.history.back();
  }

  //分页
  nzPageSizeChange(event) {
    this.randomSelect.pageSize = event;
    this.randomSelect.currentPage = 1;
    this.getElevatorListss();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.randomSelect.currentPage = event;
    this.getElevatorListss();
  }


  showModal = () => {
    this.isVisible = true;
  }

  handleOk = (e) => {
    console.log('点击了确定');
    this.isVisible = false;

    this.router.navigateByUrl("/home/plan-dict")


  }

  handleCancel = (e) => {
    this.isVisible = false;
  }
  
}
